/*
 * File     : ShortNativeStringBuffer.java
 * Created  : 13 May 2011
 *
 * Copyright © 2011 Matthew Wilson (mj. {my-surname} .uk {at} gmail.com)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.dni.internal.string;

import static com.googlecode.dni.internal.DniInternal.MEMORY_ACCESSOR;

import com.googlecode.dni.type.NativeString;
import com.googlecode.dni.type.NativeStringBuffer;
import com.googlecode.dni.type.Pointer;

/**
 * <p>
 *  Implementation of {@link NativeStringBuffer} for short-sized strings.
 * </p.
 *
 * @author Matthew Wilson
 */
public final class ShortNativeStringBuffer extends AbstractNativeStringBuffer
{

    /**
     * @param pointer
     *            the pointer to the base of the buffer
     * @param capacity
     *            the capacity in bytes
     * @param fastCharset
     *            the charset
     */
    public ShortNativeStringBuffer( final Pointer pointer, final int capacity, final FastCharset fastCharset )
    {
        super( pointer, capacity, fastCharset );
    }

    /** {@inheritDoc} */
    @Override
    public NativeStringBuffer append( final NativeString string )
    {
        long source = string.pointer().address();
        long destination = pointer().address();

        // find the end of the string buffer
        int remaining = capacity();
        while ( remaining > 0 )
        {
            if ( MEMORY_ACCESSOR.getChar( destination ) == 0 )
            {
                break;
            }
            destination += 2;
            remaining -= 2;
        }

        if ( remaining == 0 )
        {
            throw missingTerminator();
        }

        // now 'remainder' is the number of bytes (including space for
        // terminator) left in the buffer

        // how many bytes to copy?
        long sourceEnd = source;
        while ( MEMORY_ACCESSOR.getChar( sourceEnd ) != 0 )
        {
            sourceEnd += 2;
        }

        long countLong = sourceEnd - source;
        int count = (int) countLong;
        if ( count != countLong )
        {
            throw new AssertionError();
        }
        if ( count >= remaining )
        {
            throw bufferOverflow( remaining, count );
        }

        MEMORY_ACCESSOR.copyMemory( source, destination, count );

        // always terminate the string
        MEMORY_ACCESSOR.putChar( destination + count, (char) 0 );

        return this;
    }

    /** {@inheritDoc} */
    @Override
    public NativeStringBuffer append( final CharSequence charSequence )
    {
        if ( charSequence.length() == 0 )
        {
            return this;
        }

        long destination = pointer().address();

        // find the end of the string buffer
        int remaining = capacity();
        while ( remaining > 0 )
        {
            if ( MEMORY_ACCESSOR.getChar( destination ) == 0 )
            {
                break;
            }
            destination += 2;
            remaining -= 2;
        }

        if ( remaining == 0 )
        {
            throw missingTerminator();
        }

        // now 'remainder' is the number of bytes (including space for
        // terminator) left in the buffer

        // how many bytes to copy?
        String string = charSequence.toString();
        int upperBoundCount = getFastCharset().getByteCount( string );

        if ( upperBoundCount >= remaining )
        {
            // not sure whether it'll really fit...
            // try it, and correct it if it fails
            try
            {
                getFastCharset().encode( string, destination, remaining );
            }
            catch ( IllegalArgumentException exception )
            {
                // truncate the string to its original form
                MEMORY_ACCESSOR.putChar( destination, (char) 0 );
                throw exception;
            }
        }
        else
        {
            // yes, it'll fit
            getFastCharset().encode( string, destination );
        }

        return this;
    }

    /** {@inheritDoc} */
    @Override
    public int length()
    {
        long destination = pointer().address();

        int length = 0;
        while ( length < capacity() )
        {
            if ( MEMORY_ACCESSOR.getChar( destination ) == 0 )
            {
                return length;
            }
            destination += 2;
            length += 2;
        }

        throw missingTerminator();
    }

    /** {@inheritDoc} */
    @Override
    public int remaining()
    {
        return capacity() - length() - 2;
    }

    /** {@inheritDoc} */
    @Override
    public int codeSize()
    {
        return 4;
    }

    /** {@inheritDoc} */
    @Override
    public int terminatorLength()
    {
        return 2;
    }

}
